/* Copyright (C) Abu Rizal, 2009.
 * 
 * This file is part of QurText.
 * 
 * QurText is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * QurText is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with QurText. If not, see <http://www.gnu.org/licenses/>.
 */
package qurtext.factory;

import java.util.Collection;
import java.util.NoSuchElementException;

import javax.jdo.PersistenceManager;

import qurtext.domain.Profile;

public class ProfileFactory {

	@SuppressWarnings("unchecked")
	public Profile getProfile(String email) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			String query = "select from " + Profile.class.getName() + " where email=='" + email + "'";
			Profile result = ((Collection<Profile>) pm.newQuery(query)
					.execute()).iterator().next();
			return result;
		} catch (NoSuchElementException e) {
			Profile result=new Profile(email);
			pm.makePersistent(result);
			return result;
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public void saveProgress(String email, String sectionRead,
			String lastSection) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			String query = "select from " + Profile.class.getName() + " where email=='" + email + "'";
			Profile result = ((Collection<Profile>) pm.newQuery(query)
					.execute()).iterator().next();
			result.setSectionRead(sectionRead);
			result.setCurrentHistory(lastSection);
		} catch (NoSuchElementException e) {
			Profile result=new Profile(email);
			result.setSectionRead(sectionRead);
			result.setCurrentHistory(lastSection);
			pm.makePersistent(result);
		} finally {
			pm.close();
		}
	}

}
